package web

import (
	"errors"
	"fmt"
	"github.com/globalsign/mgo"
	"jgt-oper/src/bll"
	"jgt-oper/src/context"
	"jgt-oper/src/schema"
	"jgt-oper/src/util"
	"time"
)

// Park 园区管理
type Park struct {
	ParkBll         *bll.Park         `inject:""`
	EnterHistoryBll *bll.EnterHistory `inject:""`
}

// QueryPage 查询分页数据
func (a *Park) QueryPage(ctx *context.Context) error {
	ctx.WriteOperateLog("Park.QueryTree", "园区管理-查询分页数据")
	pageIndex, pageSize := ctx.GetPageIndex(), ctx.GetPageSize()
	params := schema.ParkQueryParam{
		Name:     ctx.Query("name"),
		ParentID: ctx.Query("parent_id"),
		Type:     ctx.QueryInt("type"),
	}

	total, items, err := a.ParkBll.QueryPage(params, pageIndex, pageSize)
	if err != nil {
		return ctx.ResErrInternalServer(err)
	}

	result := map[string]interface{}{
		"list": items,
		"pagination": map[string]interface{}{
			"total":    total,
			"current":  pageIndex,
			"pageSize": pageSize,
		},
	}

	return ctx.ResSuccess(result)
}

// QueryTree 查询树形数据
func (a *Park) QueryTree(ctx *context.Context) error {
	ctx.WriteOperateLog("Park.QueryTree", "园区管理-查询树形数据")
	params := schema.ParkSelectParam{
		Name: ctx.Query("name"),
	}

	items, err := a.ParkBll.QueryTree(params)
	if err != nil {
		return ctx.ResErrInternalServer(err)
	}
	return ctx.ResSuccess(items)
}

// QueryList 查询完整列表
func (a *Park) QueryList(ctx *context.Context) error {
	ctx.WriteOperateLog("Park.QueryList", "园区管理-查询完整列表")
	params := schema.ParkSelectParam{
		Name:        ctx.Query("name"),
		ParentID:    ctx.Query("parent_id"),
		Type:        ctx.QueryInt("type"),
		SalesStatus: ctx.QueryInt("sales_status"),
		LeaseStatus: ctx.QueryInt("lease_status"),
	}
	items, err := a.ParkBll.QueryList(params)
	if err != nil {
		return ctx.ResErrInternalServer(err)
	}
	return ctx.ResSuccess(items)
}

// Get 精确查询数据
func (a *Park) Get(ctx *context.Context) error {
	item, err := a.ParkBll.Get(ctx.Param("id"))
	if err != nil {
		return ctx.ResErrInternalServer(err)
	}
	return ctx.ResSuccess(item)
}

// Create 创建数据
func (a *Park) Create(ctx *context.Context) error {
	ctx.WriteOperateLog("Park.Create", "园区管理-创建数据")
	var item schema.Park
	if err := ctx.ParseJSON(&item); err != nil {
		return ctx.ResErrBadRequest(err)
	}

	item.Creator = ctx.GetUserID()

	//	检查****
	if item.Type == 10 {
		item.ParentID = ""
	}
	//检查父类
	if item.ParentID != "" {
		pitem, err := a.ParkBll.Get(item.ParentID)
		if err != nil {
			return err
		}
		if pitem == nil {
			return errors.New("父类不存在")
		}
		if (pitem.Type + 10) > item.Type {
			return errors.New("从属关系错误")
		}
	}
	//检查重复
	p := schema.ParkSelectParam{
		Name:     item.Name,
		ParentID: item.ParentID,
		Type:     item.Type,
	}
	ls, _ := a.ParkBll.QueryList(p)
	if len(ls) > 0 {
		return errors.New("建筑已存在")
	}
	levelCode, err := a.ParkBll.GetLevelCode(item.ParentID)
	if err != nil {
		return err
	}
	item.LevelCode = levelCode
	item.ID = 0
	item.RecordID = util.UUID()
	item.Created = time.Now().Unix()
	item.Deleted = 0

	//	创建门牌
	err = a.ParkBll.Create(&item)
	if err != nil {
		return ctx.ResErrInternalServer(err)
	}

	//	储存门牌历史
	insertItem := new(schema.EnterpriseParkHistory)
	insertItem.ParkID = item.RecordID
	insertItem.Created = item.Created
	insertItem.Creator = item.Creator
	insertItem.EnterpriseID = ""
	insertItem.Operate = "创建"
	insertItem.Memo = "创建门牌"
	err = a.EnterHistoryBll.InsertItem(insertItem)
	if err != nil {
		return ctx.ResErrInternalServer(err)
	}

	return ctx.ResOK()
}

// Update 更新数据
func (a *Park) Update(ctx *context.Context) error {
	ctx.WriteOperateLog("Park.Update", "园区管理-更新数据")
	var item schema.Park
	if err := ctx.ParseJSON(&item); err != nil {
		return ctx.ResErrBadRequest(err)
	}

	err := a.ParkBll.Update(ctx.Param("id"), &item)
	if err != nil {
		return ctx.ResErrInternalServer(err)
	}
	return ctx.ResOK()
}

// Delete 删除数据
func (a *Park) Delete(ctx *context.Context) error {
	ctx.WriteOperateLog("Park.Delete", "园区管理-删除数据")
	id := ctx.Param("id")
	var (
		params = schema.ParkSelectParam{
			ParentID: id,
		}
		items []*schema.ParkSelect
		err   error
	)

	items, err = a.ParkBll.QueryList(params)
	if err != nil {
		return ctx.ResErrInternalServer(err)
	}

	if len(items) > 0 {
		return ctx.ResErrBadRequest(fmt.Errorf("存在下级数据,不可删除"))
	}

	err = a.ParkBll.Delete(id)
	if err != nil {
		return ctx.ResErrInternalServer(err)
	}
	return ctx.ResOK()
}

// Enable 启用数据
func (a *Park) Enable(ctx *context.Context) error {
	ctx.WriteOperateLog("Park.Enable", "园区管理-启用数据")
	err := a.ParkBll.UpdateStatus(ctx.Param("id"), 1)
	if err != nil {
		return ctx.ResErrInternalServer(err)
	}
	return ctx.ResOK()
}

// Disable 禁用数据
func (a *Park) Disable(ctx *context.Context) error {
	ctx.WriteOperateLog("Park.Disable", "园区管理-禁用数据")
	err := a.ParkBll.UpdateStatus(ctx.Param("id"), 2)
	if err != nil {
		return ctx.ResErrInternalServer(err)
	}
	return ctx.ResOK()
}

// QueryDescendants 根据节点record_id查询其所有的后代节点
func (a *Park) QueryDescendants(ctx *context.Context) error {
	ctx.WriteOperateLog("Park.QueryDescendants", "园区管理-查询其所有的后代节点")
	//	获取参数:节点的record_id
	recordID := ctx.Param("id")
	//	初始化结果数组
	list := make([]map[string]interface{}, 0)
	items, err := a.ParkBll.QueryChildrenNodes(recordID)
	if err != nil && err != mgo.ErrNotFound {
		return ctx.ResErrInternalServer(err)
	}
	status := ctx.QueryInt("status")
	//if status == 201 || status == 202 {
	//	status = 20
	//}
	for _, item := range items {
		if item.Type != 60 { //	过滤掉楼层、区域等，只保留门牌
			continue
		}

		//	构造返回map
		tempMap := make(map[string]interface{})
		tempMap["node_name"] = item.Name
		tempMap["record_id"] = item.RecordID
		switch item.SalesStatus {
		case 10:
			tempMap["status"] = "物业自用"
			tempMap["type"] = 10
		case 20:
			if item.LeaseStatus == 10 {
				tempMap["status"] = "已出租"
				tempMap["type"] = 201
			} else if item.LeaseStatus == 20 {
				tempMap["status"] = "待出租"
				tempMap["type"] = 202
			}
		case 30:
			tempMap["status"] = "已售"
			tempMap["type"] = 30
		case 40:
			tempMap["status"] = "待售"
			tempMap["type"] = 40
		default:

		}
		//	检查是否筛选:租售状态
		if tempMap["type"] == status || status == 0 {
			list = append(list, tempMap)
		}
	}

	count10 := 0
	count201 := 0
	count202 := 0
	count30 := 0
	count40 := 0
	for _, value := range list {
		typeCode := value["type"]
		switch typeCode {
		case 10:
			count10++
		case 201:
			count201++
		case 202:
			count202++
		case 30:
			count30++
		case 40:
			count40++
		default:

		}
	}
	result := make(map[string]interface{})
	result["list"] = list
	result["10"] = count10
	result["201"] = count201
	result["202"] = count202
	result["30"] = count30
	result["40"] = count40

	return ctx.ResSuccess(result)
}
